package com.gwsdk.paysdk.utils;

import android.annotation.SuppressLint;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.gwsdk.open.GWApi;
import com.gwsdk.paysdk.Geetest.GeetestManager;
import com.gwsdk.paysdk.bean.GWRoomSeatModel;
import com.gwsdk.paysdk.bean.GWRoomInfoModel;
import com.gwsdk.paysdk.bean.HelperBean;
import com.gwsdk.paysdk.bean.LoginModel;
import com.gwsdk.paysdk.bean.MqttInfo;
import com.gwsdk.paysdk.bean.SdkDomain;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.config.GWConstant;
import com.gwsdk.paysdk.dialog.GWTipDialog;
import com.gwsdk.paysdk.entity.UserLogin;
import com.gwsdk.paysdk.http.RequestParamUtil;
import com.gwsdk.paysdk.http.RequestUtil;
import com.gwsdk.paysdk.http.process.HelperProcess;
import com.gwsdk.paysdk.http.process.SmallAccountLoginProgress;
import com.gwsdk.paysdk.service.MqttService;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.http.entity.*;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 描述：
 * 作者：钮家齐
 * 时间: 2018-11-07 14:02
 */

public class AppStatusManager {
    public int appStatus = AppStatus.STATUS_RECYVLE;    //APP状态 初始值为不在前台状态

    public static AppStatusManager appStatusManager;

    private AppStatusManager(){}
    public MqttInfo mqtt;
    public Boolean openBoxLogin = false;
    public boolean isPayFirst = false;
    public boolean loadPayWebView = false;
    public UserLogin userLogin = null;
    public HelperBean helperBean;
    public String downUrl = "https://www.genwan.com/";

    public List<GWRoomSeatModel> seatModels = new ArrayList<>();
    public GWRoomInfoModel roomInfo;

    public String version = "当前版本: V4.0.1";

    //单例模式
    public static AppStatusManager getInstance() {
        if (appStatusManager == null) {
            appStatusManager = new AppStatusManager();
            appStatusManager.startLine();
        }
        return appStatusManager;
    }

    public int getAppStatus() {
        return appStatus;
    }

    public void setAppStatus(int appStatus) {
        getDownloadUrl();
        this.appStatus = appStatus;
    }

    private GWRefreshRoomSeatListener seatListener;

    public void setSeatListener(GWRefreshRoomSeatListener seatListener) {
        this.seatListener = seatListener;
    }

    public void refreshSeatInfo(){
        if (seatListener != null){
            seatListener.onRefreshSeat();
        }
    }

    private GWTipDialog mcTipDialog;
    private String loginSmallId = "";
    public void smallAccountLogin(String smallID, FragmentManager fragmentManager){
        UserLogin userLogin = AppStatusManager.getInstance().userLogin;;
        if (userLogin == null) return;
        loginSmallId = smallID;
        SmallAccountLoginProgress progress = new SmallAccountLoginProgress();
        progress.setSmallUserId(smallID);
        progress.setUserId(userLogin.getAccountUserId());
        progress.setGameId(SdkDomain.getInstance().getGameId());
        progress.setYKLogin(userLogin.isYKLogin());
        progress.setToken(userLogin.getToken());
        progress.ageStatus = userLogin.getAgeStatus();
        progress.birthday = userLogin.getBirthday();
        progress.post(mHandler);
        mcTipDialog = new GWTipDialog.Builder().setMessage("切换小号中...").show(GWApi.getApi().getContext(),fragmentManager);
    }

    public void startLine(){
        HelperProcess helperProcess = new HelperProcess();
        helperProcess.post(handler);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != mcTipDialog) {
                mcTipDialog.dismiss();
            }
            switch (msg.what) {
                case Constant.ADD_SMALL_ACCOUNT_FAIL:  //添加小号失败
                    String tip = (String) msg.obj;
                    ToastUtil.show(GWApi.getApi().getContext(), tip);
                    break;
                case Constant.SMALL_ACCOUNT_LOGIN_SUCCESS:  //小号登录成功
                    UserLogin smallAccountLogin = (UserLogin) msg.obj;
                    LoginModel.instance().smallAccountLoginSuccess(smallAccountLogin);
                    SharedPreferencesUtils.getInstance().setLoginLastSmallAccount(GWApi.getApi().getContext(),loginSmallId);
                    SharedPreferencesUtils.getInstance().setLastLoginID(GWApi.getApi().getContext(),loginSmallId);
                    break;
                case Constant.SMALL_ACCOUNT_LOGIN_FAIL:  //小号登录失败
                    String str = (String) msg.obj;
                    ToastUtil.show(GWApi.getApi().getContext(), str);
                    break;
                case Constant.HELPER_SUCCESS:
                    helperBean = (HelperBean) msg.obj;
                    break;
                default:
                    break;
            }
        }
    };

    public void refreshUserInfo(){

        HttpUtils http = new HttpUtils();

        Map<String, String> map = new HashMap<String, String>();
        String param = RequestParamUtil.getRequestParamString(map);
        RequestParams params = new RequestParams();
        try {
            params.setBodyEntity(new StringEntity(param.toString()));
        } catch (UnsupportedEncodingException e) {
            params = null;
        }

        if (params == null) return;
        final String url = GWConstant.getInstance().getRefreshUserInfoUrl();

        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response= RequestUtil.getResponseAndUrl(responseInfo, url);
                try {
                    JSONObject json = new JSONObject(response);
                    int status=json.optInt("code");
                    if(status==200){

                        if (userLogin != null){
                            userLogin.setGroups_id(json.optJSONObject("data").optString("groups_id"));
                        }
                    }
                }  catch (Exception e) {

                }
            }
            @Override
            public void onFailure(HttpException error, String msg) {
                Log.e("downUrl",msg);
            }
        });

    }

    private void getDownloadUrl(){

        HttpUtils http = new HttpUtils();

        Map<String, String> map = new HashMap<String, String>();
        map.put("sdk_version", "1");//表示android发送的请求，固定值1
        map.put("game_id", SdkDomain.getInstance().getGameId());
        map.put("game_name", SdkDomain.getInstance().getGameName());
        map.put("game_appid", SdkDomain.getInstance().getGameAppId());
        map.put("geetest_challenge", GeetestManager.getInstance().getGeetest_challenge());
        map.put("geetest_validate", GeetestManager.getInstance().getGeetest_validate());
        map.put("geetest_seccode", GeetestManager.getInstance().getGeetest_seccode());

        String param = RequestParamUtil.getRequestParamString(map);
        RequestParams params = new RequestParams();
        try {
            params.setBodyEntity(new StringEntity(param.toString()));
        } catch (UnsupportedEncodingException e) {
            params = null;
        }

        final String url = GWConstant.getInstance().getDownLoadUrl();

        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response= RequestUtil.getResponseAndUrl(responseInfo, url);
                try {
                    JSONObject json = new JSONObject(response);
                    int status=json.optInt("code");
                    if(status==200){
                        downUrl = json.optJSONObject("data").optString("jump");
                        Log.e("downUrl",downUrl);
                    }

                }  catch (Exception e) {
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.e("downUrl",msg);
            }
        });

        final String openBoxLoginUrl = GWConstant.getInstance().getOpenBoxLoginUrl();

        http.send(HttpRequest.HttpMethod.POST, openBoxLoginUrl, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response=RequestUtil.getResponseAndUrl(responseInfo, openBoxLoginUrl);
                try {
                    JSONObject json = new JSONObject(response);
                    int status=json.optInt("code");
                    if(status==200){
                        new CountDownTimer(5000,1){
                            @Override
                            public void onTick(long millisUntilFinished) {
                            }
                            @Override
                            public void onFinish() {

                            }
                        }.start();
                        openBoxLogin = json.optInt("data",0) == 1;
                        Intent intent = new Intent("com.gwwan.com.boxLoginStatus");
                        intent.putExtra("openBoxLogin",openBoxLogin);
                        GWApi.getApi().getContext().sendBroadcast(intent);

                    }

                }  catch (Exception e) {

                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });


        http.send(HttpRequest.HttpMethod.POST, GWConstant.getInstance().getSensitiveUrl(), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response=RequestUtil.getResponseAndUrl(responseInfo, GWConstant.getInstance().getSensitiveUrl());
                try {
                    JSONObject json = new JSONObject(response);
                    int status=json.optInt("code");
                    if(status==200){
                        JSONArray array =  json.getJSONArray("data");
                        Set<String> set = new HashSet<>();
                        for (int i=0;i<array.length();i++){
                            set.add(array.optString(i));
                        }
                        SensitiveWordsUtils.init(set);
                    }
                }  catch (Exception e) {

                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    private Handler handler = new Handler();
    private boolean isStop = false;
    private int millis = 120000;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (isStop) return;
            if (userLogin == null) return;
            postOnline();
            handler.postDelayed(runnable,millis);
        }
    };

    public void getRoomInfo(){

        if (userLogin == null) return;
        HttpUtils http = new HttpUtils();

        Map<String, String> map = new HashMap<String, String>();
        String param = RequestParamUtil.getRequestParamString(map);
        RequestParams params = new RequestParams();
        try {
            params.setBodyEntity(new StringEntity(param.toString()));
        } catch (UnsupportedEncodingException e) {
            params = null;
        }

        if (params == null) return;
        final String url = GWConstant.getInstance().getRoomInfoUrl();

        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response= RequestUtil.getResponseAndUrl(responseInfo, url);
                try {
                    JSONObject json = new JSONObject(response);
                    int status=json.optInt("code");
                    if(status==200){
                        GWRoomInfoModel model = JsonUtil.toObj(json.getJSONObject("data").toString(), GWRoomInfoModel.class);
                        List<GWRoomSeatModel> seats = new ArrayList<>();
                        for (GWRoomSeatModel m : model.msg_list) {
                            m.isSeat = false;
                            if (m.user_list != null){
                                m.isSeat = true;
                                m.head_picture = m.user_list.head_img;
                                m.nickname = m.user_list.nickname;
                            }
                            seats.add(m);
                        }
                        Collections.sort(seats);
                        seatModels = seats;
                        if (model.room_id > 0){
                            MqttService.subscribeRoom(model.room_id + "");
                        }
                        roomInfo = model;
                        refreshSeatInfo();
                    }
                }  catch (Exception e) {

                }
            }
            @Override
            public void onFailure(HttpException error, String msg) {
                Log.e("downUrl",msg);
            }
        });

    }

    private void postOnline(){

        HttpUtils http = new HttpUtils();

        Map<String, String> map = new HashMap<String, String>();
        String param = RequestParamUtil.getRequestParamString(map);
        RequestParams params = new RequestParams();
        try {
            params.setBodyEntity(new StringEntity(param.toString()));
        } catch (UnsupportedEncodingException e) {
            params = null;
        }

        final String url = GWConstant.getInstance().getOnLineUrl();

        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response=RequestUtil.getResponseAndUrl(responseInfo, url);
                Log.d("postOnline",response);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.e("downUrl",msg);
            }
        });
    }

    public void startTime(){
        if (userLogin == null) return;
        if (isStop){
            isStop = false;
        }
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable,millis);
    }

    public void stopTime(){
        isStop = true;
        handler.removeCallbacks(runnable);
    }


    public interface GWRefreshRoomSeatListener{
        void onRefreshSeat();
    }

}
